# -*- coding: UTF-8 -*-
import struct
#from bp import *
from datetime import datetime

import gzip
import os
import urllib

import numpy

# 数据加载器基类
class Loader(object):

    def __init__(self, path, count):
        '''
        初始化加载器
        path: 数据文件路径
        count: 文件中的样本个数
        '''
        self.path = path
        self.count = count

    def __init__(self,path):
        self.path = path

    def get_file_content(self):
        '''
        读取文件内容
        '''
        f = open(self.path, 'rb')
        content = f.read()
        f.close()
        return content

    def to_int(self, byte):
        '''
        将unsigned byte字符转换为整数
        '''
        return struct.unpack('B', byte)[0]


def _read32(bytestream):
  dt = numpy.dtype(numpy.uint32).newbyteorder('>')
  #return numpy.frombuffer(bytestream.read(4), dtype=dt) old ver.
  return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]


# 图像数据加载器
class ImageLoader(Loader):

    def extract_images(self,filename):
        """Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
        print('Extracting', filename)
        with gzip.open(filename) as bytestream:
            magic = _read32(bytestream)
            if magic != 2051:
                raise ValueError(
                    'Invalid magic number %d in MNIST image file: %s' %
                    (magic, filename))
            num_images = _read32(bytestream)
            rows = _read32(bytestream)
            cols = _read32(bytestream)
            buf = bytestream.read(rows * cols * num_images)
            data = numpy.frombuffer(buf, dtype=numpy.uint8)
            #data = data.reshape(num_images, rows, cols, 1)
            data = data.reshape(num_images,rows * cols)
            return data

    def get_picture(self, content, index):
        '''
        内部函数，从文件中获取图像
        '''
        start = index * 28 * 28 + 16
        picture = []
        for i in range(28):
            picture.append([])
            for j in range(28):
                picture[i].append(
                    self.to_int(content[start + i * 28 + j]))
        return picture

    def get_one_sample(self, picture):
        '''
        内部函数，将图像转化为样本的输入向量
        '''
        sample = []
        for i in range(28):
            for j in range(28):
                sample.append(picture[i][j])
        return sample

    def load(self):
        '''
        加载数据文件，获得全部样本的输入向量
        '''
        content = self.get_file_content()
        data_set = []
        for index in range(self.count):
            data_set.append(
                self.get_one_sample(
                    self.get_picture(content, index)))
        return data_set

    def loadx(self):
        return self.extract_images(self.path)


# 标签数据加载器
class LabelLoader(Loader):

    def dense_to_one_hot(self, labels_dense, num_classes=10):
        """Convert class labels from scalars to one-hot vectors."""
        num_labels = labels_dense.shape[0]
        index_offset = numpy.arange(num_labels) * num_classes
        labels_one_hot = numpy.zeros((num_labels, num_classes))
        labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
        return labels_one_hot

    def extract_labels(self, filename, one_hot=False):
        """Extract the labels into a 1D uint8 numpy array [index]."""
        print('Extracting', filename)
        with gzip.open(filename) as bytestream:
            magic = _read32(bytestream)
            if magic != 2049:
                raise ValueError(
                    'Invalid magic number %d in MNIST label file: %s' %
                    (magic, filename))
            num_items = _read32(bytestream)
            buf = bytestream.read(num_items)
            labels = numpy.frombuffer(buf, dtype=numpy.uint8)
            if one_hot:
                return self.dense_to_one_hot(labels)
            return labels

    def load(self):
        '''
        加载数据文件，获得全部样本的标签向量
        '''
        content = self.get_file_content()
        labels = []
        for index in range(self.count):
            labels.append(self.norm(content[index + 8]))
        return labels

    def loadx(self,one_hot):
        '''
        改写一下load
        :return: 
        '''
        return self.extract_labels(self.path,one_hot)

    def norm(self, label):
        '''
        内部函数，将一个值转换为10维标签向量
        '''
        label_vec = []
        label_value = self.to_int(label)
        for i in range(10):
            if i == label_value:
                label_vec.append(0.9)
            else:
                label_vec.append(0.1)
        return label_vec


datafolder = '../data/MNIST_data/'


def get_training_data_set():
    '''
    获得训练数据集
    '''
    image_loader = ImageLoader( datafolder + 'train-images-idx3-ubyte.gz', 60000)
    label_loader = LabelLoader( datafolder + 'train-labels-idx1-ubyte.gz', 60000)
    return image_loader.load(), label_loader.load()


def get_test_data_set():
    '''
    获得测试数据集
    '''
    image_loader = ImageLoader( datafolder + 't10k-images-idx3-ubyte.gz', 10000)
    label_loader = LabelLoader( datafolder + 't10k-labels-idx1-ubyte.gz', 10000)
    return image_loader.load(), label_loader.load()


def get_training_data_set_x(one_hot = False):
    '''
    获得训练数据集
    '''
    image_loader = ImageLoader( datafolder + 'train-images-idx3-ubyte.gz')
    label_loader = LabelLoader( datafolder + 'train-labels-idx1-ubyte.gz')
    return image_loader.loadx(), label_loader.loadx(one_hot)


def get_test_data_set_x(one_hot = False):
    '''
    获得测试数据集
    '''
    image_loader = ImageLoader( datafolder + 't10k-images-idx3-ubyte.gz')
    label_loader = LabelLoader( datafolder + 't10k-labels-idx1-ubyte.gz')
    return image_loader.loadx(), label_loader.loadx(one_hot)

import data.dataset as dd

def get_mnist_set(one_hot = False):
    '''
    获得训练数据集
    '''
    trimages = ImageLoader( datafolder + 'train-images-idx3-ubyte.gz').loadx()
    trlabels = LabelLoader( datafolder + 'train-labels-idx1-ubyte.gz').loadx(one_hot)
    tsimages = ImageLoader( datafolder + 't10k-images-idx3-ubyte.gz').loadx()
    tslabels = LabelLoader( datafolder + 't10k-labels-idx1-ubyte.gz').loadx(one_hot)

    # read train data
    class DataSets(object):
        pass
    data_sets = DataSets()

    data_sets.train = dd.DataSet(trimages,trlabels)
    data_sets.test = dd.DataSet(tsimages,tslabels)

    return data_sets